package org.redmagic.client;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.redmagic.client.api.Location;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class RedMagicConfiguration {

	private List<Location> locations;
	
	public RedMagicConfiguration(String configurationLocation) {
		
		locations = new ArrayList<Location>();
		
		if (configurationLocation == null) {
			throw new NullPointerException("Configuration location is required");
		}
		
		try {
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setNamespaceAware(true);
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			
			parseLocations(docBuilder.parse(new File(configurationLocation)));
			
		} catch (Exception e) {
			
			throw new RuntimeException("Unable to prepare configuration", e);
		}
	}
	
	public Location getNextLocation() {

		if (locations.isEmpty()) {
			return null;
		} else {
			return locations.remove(0);
		}
	}
	
	private void parseLocations(Document configuration) {
		
		// THIS CURRENTLY ONLY SUPPORTS WEB LOCATIONS
		NodeList webLocations = configuration.getElementsByTagName("webLocation");
		for (int i = 0; i < webLocations.getLength(); i++) {
			
			Element webLocation = (Element) webLocations.item(i);
			locations.add(WebLocation.parseWebLocation(webLocation));
		}
	}
}


























